﻿using IdentityModel.Client;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SJ.Platform.Common;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.MenuManager;
using SJ.Platform.EFCore.Model.UserManager;
using SJ.Platform.Extend;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.SysUserExt;
using SJ.Platform.Extend.Response;
using System.Security.Claims;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SJ.Platform.Api.Controllers.Login
{
    /// <summary>
    /// 用户登录接口
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/Login")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class LoginController : ControllerBase
    {
        private readonly Sys_MenuHandle sys_MenuHandle;
        private readonly Sys_RoleHandle sys_RoleHandle;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="configuration">配置</param>
        public LoginController(SJDBContext dbContext, IConfiguration configuration)
        {
            sys_MenuHandle = new Sys_MenuHandle(dbContext);
            sys_RoleHandle = new Sys_RoleHandle(dbContext);
            _configuration = configuration;
        }

        /// <summary>
        /// 登录 
        /// </summary>
        /// <param name="username">登录账号</param>
        /// <param name="password">登陆密码</param>
        /// <returns></returns>
        [HttpGet("UserLogin/{username}/{password}")]
        [AllowAnonymous]
        public IActionResult UserLogin(string username, string password)
        {
            string result = TokenHandle.GetToken(_configuration["IdentityServerUrl"], username, password);
            if (!string.IsNullOrWhiteSpace(result))
            {
                var claims = TokenHandle.ParseToken(result);
                // 提取用户信息
                var userId = claims.FirstOrDefault(c => c.Type == "UserId")?.Value; // 用户ID
                var realName = claims.FirstOrDefault(c => c.Type == "RealName")?.Value; // 真实姓名
                var orgId = claims.FirstOrDefault(c => c.Type == "OrgId")?.Value;//组织机构ID
                var orgName = claims.FirstOrDefault(c => c.Type == "OrgName")?.Value;//组织机构名称
                var sex = claims.FirstOrDefault(c => c.Type == "Sex")?.Value; // 性别
                var birthday = claims.FirstOrDefault(c => c.Type == "Birthday")?.Value; // 出生日期
                var isUsed = claims.FirstOrDefault(c => c.Type == "IsUsed")?.Value; // 是否启用

                SysUserExtend sys_User = new SysUserExtend() { Id = userId, RealName = realName, OrgId = orgId, OrgName = orgName, Sex = Convert.ToSByte(sex), IsUsed = Convert.ToSByte(isUsed) };
                if (!string.IsNullOrWhiteSpace(birthday))
                {
                    sys_User.Birthday = Convert.ToDateTime(birthday);
                }

                //查询菜单
                if (sys_User.menuList == null)
                {
                    sys_User.menuList = new List<SysMenuExtend>();
                }
                sys_User.menuList = sys_MenuHandle.GetAllByUserId(sys_User.Id).Result;

                //查询角色
                if (sys_User.roleList == null)
                {
                    sys_User.roleList = new List<EFCore.Model.RoleManager.SysRole>();
                }
                sys_User.roleList = sys_RoleHandle.GetAllByUserIdAsync(userId).Result;

                return Ok(ApiLoginResponse<SysUserExtend>.SetResponse(ApiResponseStatus.Success, "登录成功", result, sys_User));
            }

            return BadRequest(ApiLoginResponse<object>.SetResponse(ApiResponseStatus.NoData, "Invalid username or password", "", "")); // 返回 400 Bad Request 并附带 ApiResponse 对象
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpGet("UserLogout")]
        public IActionResult UserLogout()
        {
            // 在这里执行退出逻辑，例如清除当前用户的会话信息或其他必要的操作

            return Ok(ApiLoginResponse<object>.SetResponse(ApiResponseStatus.Success, "退出成功", "", "")); // 返回成功的响应
        }
    }
}